<template>
  <div>
    <div class="top">
      <div class="search">
        <el-form :inline="true">
          <el-form-item>
            <el-button class="add" type="primary" @click="addRole()"
            >{{ t('addRole') }}
            </el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-table class="table_content" v-loading="loadingListData" :data="state.roleList" :border="true">
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="role_name" :label="t('roleName')"></el-table-column>
      <el-table-column :label="t('op')">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="modifyPermission(row)">{{ t('configPermission') }}</el-button>
          <!--          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="state.total"
    >
    </el-pagination>
    <!-- 新增or编辑 -->
    <!-- 弹窗 -->
    <el-dialog :title="dialogTitle" v-loading="addDialogLoading" v-model="dialogVisible" width="500">
      <el-form :model="formItemData">
        <el-form-item :label="t('roleName')">
          <el-input v-model="formItemData.role_name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">{{ t('cancel') }}</el-button>
        <el-button type="primary" @click="handleSubmit()">{{ t('submit') }}</el-button>
      </template>
    </el-dialog>
    <!-- 配置权限 -->
    <el-dialog v-model="permissionDialogState.dialogVisible" :title="t('configPermission')">
      <el-checkbox-group v-model="permissionDialogState.checkedPermissions">
        <el-checkbox
          v-for="permission in permissionDialogState.roleList"
          :key="permission.uri"
          :label="permission.uri"
          :disabled="permissionDialogState.isLoading"
        >
          {{ permission.access_name }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="permissionDialogState.dialogVisible = false">{{ t('cancel') }}</el-button>
        <el-button type="primary" @click="confirmPermissions">{{ t('confirm') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, toRefs, onMounted } from 'vue'
import {
  ElTable,
  ElTableColumn,
  ElPagination,
  ElTag,
  ElButton, ElMessage
} from 'element-plus'

import { doGetRoleList, doAddRole, doGetAccessByRole, doGetAccessList, doEditAccessByRole } from '@/api/role'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
// 弹窗显示状态
const dialogVisible = ref(false)
// 弹窗标题
const dialogTitle = ref('')
// 弹窗加载状态
const addDialogLoading = ref(false)
const loadingListData = ref(false)

const permissionDialogState = reactive({
  dialogVisible: false,
  roleList: [], // 可配置的总权限列表
  checkedPermissions: [], // 已经勾选的权限
  isLoading: false // 是否正在加载数据
})

onMounted(() => {
  getRoleList()
  getAccessList()
})

// 获取角色列表
const getRoleList = () => {
  loadingListData.value = true
  doGetRoleList(state.currentPage, state.pageSize).then((res) => {
    state.roleList = res.role_list
    state.total = res.total
  }).catch((err) => {
    console.log(err)
  }).finally(() => {
    loadingListData.value = false
  })
}

const getAccessList = () => {
  doGetAccessList().then((res) => {
    permissionDialogState.roleList = res.access_list
  }).catch((err) => {
    console.log(err)
  })
}

// 表单数据
const formItemData = ref({
  id: null,
  role_name: ''
})

const state = reactive({
  roleList: [],
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const addRole = () => {
  dialogTitle.value = t('addRole')
  formItemData.value = {
    id: null,
    role_name: ''
  }
  dialogVisible.value = true
}

const handleSubmit = () => {
  addDialogLoading.value = true
  doAddRole(formItemData.value.role_name).then((res) => {
    addDialogLoading.value = false
    dialogVisible.value = false
    getRoleList()
  }).catch((err) => {
    addDialogLoading.value = false
    console.log(err)
  })
}

const confirmPermissions = () => {
  permissionDialogState.isLoading = true
  console.log('已勾选的权限:', permissionDialogState.checkedPermissions)
  doEditAccessByRole(formItemData.value.id,
    permissionDialogState.checkedPermissions.length == 0 ? ['x'] : permissionDialogState.checkedPermissions)
    .then((res) => {
      permissionDialogState.isLoading = false
      permissionDialogState.dialogVisible = false
      ElMessage.success(t('configSuccess'))
    }).catch((err) => {
    permissionDialogState.isLoading = false
    console.log(err)
  })
}

const modifyPermission = (row) => {
  loadingListData.value = true
  doGetAccessByRole(row.id).then((res) => {
    formItemData.value.id = row.id
    permissionDialogState.checkedPermissions = res.role_list.map((item) => item.uri)
    permissionDialogState.dialogVisible = true
  }).catch((err) => {
    console.log(err)
  }).finally(() => {
    loadingListData.value = false
  })
}

const handleSizeChange = (newSize) => {
  state.pageSize = newSize
}

const handleCurrentChange = (newPage) => {
  state.currentPage = newPage
  getRoleList()
}

// 导出响应式状态的引用
const { currentPage, pageSize } = toRefs(state)
</script>

<style scoped lang="scss">
.top {
  width: 98%;
  margin-top: 28px;
  margin-bottom: 10px;

  .status {
    width: 180px;
  }
}

.table_content {
  width: 98%;
  margin-top: 20px;
}
</style>
